package cn.stylefeng.guns.sys.modular.tao.service.serviceImpl;

import cn.stylefeng.guns.sys.modular.api.controller.ApiController;
import cn.stylefeng.guns.sys.modular.api.sdk.Utils;
import cn.stylefeng.guns.sys.modular.tao.entity.Member;
import cn.stylefeng.guns.sys.modular.tao.entity.WxUser;
import cn.stylefeng.guns.sys.modular.tao.entity.entityExtend.WxUserExtends;
import cn.stylefeng.guns.sys.modular.tao.mapper.MemberMapper;
import cn.stylefeng.guns.sys.modular.tao.mapper.WxUserMapper;
import cn.stylefeng.guns.sys.modular.tao.service.WxUserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

@Service
public class WxUserServiceImpl implements WxUserService {

    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private MemberMapper memberMapper;

    /**
     * 注册
     *
     * @param map
     * @return
     */
    @Override
    public ResponseData register(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        String sql = "";
        try {
            //查询用户是否存在
            List<WxUser> wxUser = wxUserMapper.getUsr(map.get("registerNumber").toString());
            if (wxUser.size() > 0) {
                data.setCode(500);
                data.setMessage("该用户已存在");
            } else {
                String createTime = Utils.getTime();
                String delSign = "0";
                String memberGrade = "0";
                //加密
                String password = Utils.getEncryptedPwd(map.get("loginPassword").toString());
                sql += " (create_time,del_sign,register_number,member_grade,login_password,promoter_id) values ('" + createTime + "','" + delSign + "','" + map.get("registerNumber") + "','" + memberGrade + "','" + password + "'," + map.get("promoterId") + " )";
                wxUserMapper.register(sql);
                data.setCode(200);
                data.setMessage("注册成功");
            }
        } catch (Exception e) {
            data.setCode(500);
            data.setMessage("注册失败");
        }
        return data;
    }

    /**
     * 账号登录
     *
     * @param map
     * @return
     */
    @Override
    public ResponseData loginBypassword(Map<String, String> map) {
        ResponseData data = new ResponseData();

        try {
            //查询用户是否存在
            List<WxUser> wxUserList = wxUserMapper.getUsr(map.get("registerNumber"));
            if (wxUserList.size() > 0) {
                if (Utils.validPassword(map.get("loginPassword"), wxUserList.get(0).getLoginPassword())) {
                    data.setCode(200);
                    data.setMessage("登陆成功");
                    data.setData(wxUserList.get(0));
                } else {
                    data.setCode(500);
                    data.setMessage("账号或密码错误");
                }
            } else {
                data.setMessage("请先注册");
                data.setCode(500);
            }
        } catch (NoSuchAlgorithmException e) {
            data.setMessage("数据出错");
            data.setCode(500);
        } catch (UnsupportedEncodingException e) {
            data.setMessage("数据出错");
            data.setCode(500);
        }

        return data;
    }

    /**
     * 微信登录
     *
     * @param map
     * @return
     */
    @Override
    public ResponseData loginByWx(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        WxUser wxUser = new WxUser();
        String registerNumber = null;
        try {
            //获取微信绑定手机号
            registerNumber = ApiController.getWxPhoneNumber(map.get("code").toString(), map.get("encryptedData").toString(), map.get("iv").toString());
            if (StringUtils.hasText(registerNumber)) {
                //查询用户是否存在
                List<WxUser> wxUserList = wxUserMapper.getUsr(registerNumber);
                if (wxUserList.size() > 0) {
                    data.setCode(200);
                    data.setMessage("登陆成功");
                    data.setData(wxUserList.get(0));
                } else {
                    String createTime = Utils.getTime();
                    String delSign = "0";
                    String memberGrade = "0";
                    String openId = ApiController.getOpenIdByCode(map.get("code").toString());
                    wxUser.setCreateTime(createTime);
                    wxUser.setDelSign(delSign);
                    wxUser.setMemberGrade(memberGrade);
                    wxUser.setOpenId(openId);
                    wxUser.setRegisterNumber(map.get("registerNumber").toString());
                    wxUser.setPromoterId(Long.valueOf(String.valueOf(map.get("promoterId"))));
                    //注册新账号
                    wxUserMapper.addUserByWx(wxUser);
                    data.setCode(200);
                    data.setMessage("登陆成功");
                    data.setData(wxUser);
                }
            } else {
                data.setCode(500);
                data.setMessage("数据出错");
            }
        } catch (Exception e) {
            data.setCode(500);
            data.setMessage("数据出错");
        }
        return data;
    }

    /**
     * 修改密码
     *
     * @param map
     * @return
     */
    @Override
    public ResponseData updateLoginPasswoed(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        String password = null;
        try {
            if (Utils.checkStringIsNotNull(map.get("oldPassWord").toString())) {
                //验证旧密码
                WxUser wxUser = wxUserMapper.getPasswordById(map.get("id"));
                if (wxUser != null) {
                    if (Utils.checkStringIsNotNull(wxUser.getLoginPassword())) {
                        if (Utils.validPassword(map.get("oldPassWord").toString(), wxUser.getLoginPassword())) {
                            //修改密码
                            password = Utils.getEncryptedPwd(map.get("loginPassWord").toString());
                            wxUserMapper.updatePassword(map.get("id"), password);
                            data.setCode(200);
                            data.setMessage("密码修改成功");
                        } else {
                            data.setCode(500);
                            data.setMessage("密码输入错误");
                        }
                    } else {
                        data.setCode(500);
                        data.setMessage("数据出错");
                    }
                } else {
                    data.setCode(500);
                    data.setMessage("数据出错");
                }
            } else {
                //修改密码
                wxUserMapper.updatePassword(map.get("id"), map.get("loginPassWord"));
                data.setCode(200);
                data.setMessage("密码修改成功");
            }
        } catch (NoSuchAlgorithmException e) {
            data.setCode(500);
            data.setMessage("数据出错");
        } catch (UnsupportedEncodingException e) {
            data.setCode(500);
            data.setMessage("数据出错");
        }
        return data;
    }

    /**
     * 修改身份证号
     *
     * @param map
     * @return
     */
    @Override
    public ResponseData updateAuthentication(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        try {
            //查询用户是否存在
            WxUser wxUser = wxUserMapper.getUserById(map.get("id"));
            if (wxUser != null) {
                //修改认证信息
                wxUserMapper.updateIdNumber(map.get("id"), map.get("idNumber"),map.get("realName"));
                data.setCode(200);
                data.setMessage("修改成功");
            } else {
                data.setCode(500);
                data.setMessage("用户不存在");
            }
        } catch (Exception e) {
            data.setCode(500);
            data.setMessage("数据出错");
        }
        return data;
    }

    /**
     * 会员升级
     *
     * @param map
     * @return
     */
    @Override
    public ResponseData updateMember(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        Member member = new Member();
        try {
            //查询用户是否存在
            WxUser wxUser = wxUserMapper.getUserById(map.get("id"));
            if (wxUser != null) {
                int gragde = Integer.parseInt(wxUser.getMemberGrade());
                if(gragde==3){
                    data.setCode(500);
                    data.setMessage("不可再升级会员");
                    return data;
                }
                //修改会员等级
                wxUserMapper.updateMember(map.get("id"), map.get("memberGrade"));
                //查询是否存在会员信息
                Member memberInfo = memberMapper.getMember(map.get("id"));
                if (memberInfo != null) {
                    Long integral = Long.parseLong("0");
                    member.setId(Long.valueOf(String.valueOf(map.get("id"))));
                    member.setUpdateTime(Utils.getTime());
                    member.setCommission(new BigDecimal("0"));
                    member.setPurchaseQuota(new BigDecimal("0"));
                    member.setIntegral(integral);
                    memberMapper.editMember(member);
                } else {
                    //会员表创建会员数据
                    member.setId(wxUser.getId());
                    member.setCreateTime(Utils.getTime());
                    member.setDelSign("0");
                    member.setCommission(new BigDecimal("0"));
                    member.setPurchaseQuota(new BigDecimal("0"));
                    memberMapper.addMember(member);
                    data.setCode(200);
                    data.setMessage("修改成功");
                }
            } else {
                data.setCode(500);
                data.setMessage("用户不存在");
            }
        } catch (Exception e) {
            data.setCode(500);
            data.setMessage("数据出错");
        }
        return data;

    }


    /**
     * 取消会员
     *
     * @param map
     * @return
     */
    @Override
    public ResponseData deleteMember(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        WxUser wxUserInfo = new WxUser();
        Member memberInfo = new Member();
        try {
            //查询用户是否存在
            WxUser wxUser = wxUserMapper.getUserById(map.get("id"));
            if (wxUser != null) {
                wxUserInfo.setId(Long.valueOf(String.valueOf(map.get("id"))));
                wxUserInfo.setMemberGrade("0");
                //用户表修改会员状态
                wxUserMapper.deleteMember(wxUserInfo);
                memberInfo.setDelSign("1");
                memberInfo.setId(Long.valueOf(String.valueOf(map.get("id"))));
                memberInfo.setUpdateTime(Utils.getTime());
                //会员表修改会员状态
                memberMapper.deleteMemberInfo(memberInfo);
                data.setCode(200);
                data.setMessage("修改成功");
            } else {
                data.setCode(500);
                data.setMessage("用户不存在");
            }
        } catch (NumberFormatException e) {
            data.setCode(500);
            data.setMessage("修改失败");
        }
        return data;
    }

    /**
     * 生成二维码
     *
     * @param map
     * @return
     */
    @Override
    public ResponseData getWxUserQRCode(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        String accessToken = null;
        String pictureUrl = null;
        try {
            accessToken = ApiController.getAccessToken();
            pictureUrl = ApiController.postMiniqrQr(accessToken, map.get("id").toString());
            data.setData(pictureUrl);
            data.setCode(200);
            data.setMessage("生成成功");
        } catch (Exception e) {
            data.setCode(500);
            data.setMessage("生成失败");
        }
        return data;
    }

    /**
     * 查询用户信息
     * @param map
     * @return
     */
    @Override
    public ResponseData findUserInfo(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        try {
            WxUserExtends userInfo = wxUserMapper.findUserInfo(map.get("id"));
            data.setMessage("查询成功");
            data.setCode(200);
            data.setData(userInfo);
        } catch (Exception e) {
           data.error(500,"查询失败");
        }
        return data;
    }

    @Override
    public WxUser getUserById(String userId) {

        return wxUserMapper.getUserById(userId);
    }

    @Override
    public int update(WxUser userById) {
        return wxUserMapper.update(userById);
    }

    @Override
    public void upgradeMember(WxUser wxuser) {
        wxUserMapper.upgradeMember(wxuser);
    }

    @Override
    public List<WxUser> memberGrade(WxUser wxuser) {
        return wxUserMapper.memberGrade(wxuser);
    }

    @Override
    public void updateaddUseMonye(String openid, double userTotal, double quotaTotal) {
        wxUserMapper.updateaddUseMonye(openid, userTotal, quotaTotal);
    }

    @Override
    public void shouQuan(WxUser wxuser) {
        wxUserMapper.shouQuan(wxuser);
    }

    @Override
    public List<WxUser> memberTime(WxUser wxuser) {
        return wxUserMapper.memberTime(wxuser);
    }

    @Override
    public List<WxUser> grantMember(WxUser wxuser) {
        return wxUserMapper.grantMember(wxuser);
    }

    @Override
    public List<WxUser> isGrant(WxUser wxuser) {
        return wxUserMapper.isGrant(wxuser);
    }

    @Override
    public List<WxUser> userMoney(WxUser wxuser) {
        return wxUserMapper.userMoney(wxuser);
    }
}
